<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="./js/html2canvas.js"></script>
    <script type="text/javascript" src="./js/canvas2image.js"></script>
</head>
<body>
<div id="view">
    <h1>第一个</h1>
    <h2>第二个</h2>
    <h3>第三个</h3>
    <h4>第四个</h4>
</div>

<div id="images"></div>

<input type="button" value="截图" onclick="takeScreenshot()">

</body>
</html>

<script type="text/javascript">
    function takeScreenshot() {
        console.log('test');
        html2canvas(document.getElementById('view'), {useCORS: true}).then(canvas => {
            //添加属性
            canvas.setAttribute('id', 'thecanvas');
            //读取属性值
            var value = canvas.getAttribute('id');
            document.getElementById('images').appendChild(canvas);
            var oCanvas = document.getElementById("thecanvas");
            /*自动保存为png*/
            // 获取图片资源
            var img_data1 = Canvas2Image.saveAsPNG(oCanvas, true).getAttribute('src');
            saveFile(img_data1, 'abc');
        })
    }

    var saveFile = function (data, filename) {
        var save_link = document.createElement('a');
        save_link.href = data;
        save_link.download = filename;
        save_link.style.display = 'none';
        var event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        save_link.dispatchEvent(event);
    }
</script>